在从后台数据获取时,发现并没有自己想要的字段,原因是后台使用jsonView并没有包含自己想要的字段.

动态jsonView

一开始想重新写一个方法,使用新定义的jsonView,但是功能都一样,感觉没有必要.因为就是需要使用不同的jsonView,所以考虑能不能根据情况使用不同的jsonView返回数据.

解决

在stackoverflow上找到了解决方法,对此他有一段描述:

On the off chance someone else wants to achieve the same thing, it actually is very simple.

You can directly return aorg.springframework.http.converter.json.MappingJacksonValue instance >from your controller that contains both the object that you want to serialise and the view >class.

This will be picked up by the org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter#writeInternal method and the appropriate view will be used.

大意是说可以通过返回MappingJacksonValue这个类的实例来解决这个问题,并且给出了实例代码:

@RequestMapping(value = "/accounts/{id}", method = GET, produces = APPLICATION_JSON_VALUE)
public MappingJacksonValue getAccount(@PathVariable("id") String accountId, @AuthenticationPrincipal User user) {
    final Account account = accountService.get(accountId);
    final MappingJacksonValue result = new MappingJacksonValue(account);
    final Class<? extends View> view = accountPermissionsService.getViewForUser(user);
    result.setSerializationView(view);
    return result;
}

首先就是创建MappingJacksonValue类实例,在构造函数中传入要序列化的对象,之后调用setSerializationView方法传入jsonView的class对象就行了,AbstractJackson2HttpMessageConverter类会处理这个对象并根据传入jsonView来序列化对象.

#最终
最终代码:
@GetMapping
    @ResponseStatus(HttpStatus.OK)
    private MappingJacksonValue getAll(@RequestParam(required = false, value = "isCascade", defaultValue = "false") boolean cascade) {
        List<College> collegeList = collegeService.getAllCollege();
        MappingJacksonValue result = new MappingJacksonValue(collegeList);
        if (cascade) {
            result.setSerializationView(CollegeJsonView.getCascadeMessage.class);
        } else {
            result.setSerializationView(CollegeJsonView.getAll.class);
        }
        return result;
    }

根据isCascade参数来判断是否返回自定义的josnView数据。


鲸冬香
456 声望27 粉丝